package com.ibm.commerce.url.tasks.cmc;

import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.UnsupportedEncodingException;
import java.util.LinkedHashMap;
import java.util.Map;

import com.ibm.commerce.url.exception.TaskFailException;
import com.ibm.commerce.url.harness.HTTPFileBody;
import com.ibm.commerce.url.harness.HTTPMultipartEntity;
import com.ibm.commerce.url.harness.HTTPStringBody;
import com.ibm.commerce.url.harness.URLTestTask;
import com.ibm.wc.test.exception.DatablockMissingException;

public class CMCUploadAttachment extends URLTestTask{
	/********************************************************
	 * This file demos an simple end-2-end scenario for uploading a file in CMC.
	 * This is not a clean task, there are some hardcodings including hostname / storeId. It's
	 * for demo purpose only. A fake file is created everytime inside this scenario for demo purpose
	 * whenever this scenario is executed, we will upload the fake file to server side.
	 * 
	 * The file upload is a little tricky, it cannot be done with normal POST method. We are using MultipartEntity to compose
	 * the http request, according to what HTTP Protocol defines. 
	 * 
	 * References: http://www.w3.org/Protocols/rfc2616/rfc2616.html
	 *  
	 ********************************************************/
	public static final String INPUT_PARAMETER_NAME_LOGONID = "logonId";
	public static final String INPUT_PARAMETER_NAME_LOGONPASSWORD = "logonPassword";
	
	private static CMCUploadAttachment instance = new CMCUploadAttachment();
	private CMCUploadAttachment(){}
	
	public static void execute() throws TaskFailException, DatablockMissingException {
		instance.runTask();
	}
	public static void execute(int counterIndex) throws TaskFailException, DatablockMissingException {
		instance.runTask(counterIndex);
	}
	
	private static Map<String, String> CMCLogonStep2_FORM = new LinkedHashMap<String, String>();
	static{
		CMCLogonStep2_FORM.put("logonId","");
		CMCLogonStep2_FORM.put("password", "");
	}
	
	private static Map<String, String> CMCGetResourceBundleStep3_FORM = new LinkedHashMap<String, String>();
	static{
//		CMCLogonStep3_FORM.put("BrowserOk","true");
//		CMCLogonStep3_FORM.put("XMLFile","common.mcLogon");
//		CMCLogonStep3_FORM.put("slurl","StoreLanguageSelection");
//		CMCLogonStep3_FORM.put("mcurl","MerchantCenterView?XMLFile=common.merchantCenter");
//		CMCLogonStep3_FORM.put("reLogonURL","ToolsLogon?XMLFile=common.mcLogon");		
//		CMCLogonStep3_FORM.put("URL","StoreLanguageSelection");
//		CMCLogonStep3_FORM.put("logonId","");
//		CMCLogonStep3_FORM.put("logonPassword","");
	}
	
	private static Map<String, String> CMCFindStoreStep4_FORM = new LinkedHashMap<String, String>();
	static{
//		CMCLogonStep3_FORM.put("BrowserOk","true");
//		CMCLogonStep3_FORM.put("XMLFile","common.mcLogon");
//		CMCLogonStep3_FORM.put("slurl","StoreLanguageSelection");
//		CMCLogonStep3_FORM.put("mcurl","MerchantCenterView?XMLFile=common.merchantCenter");
//		CMCLogonStep3_FORM.put("reLogonURL","ToolsLogon?XMLFile=common.mcLogon");		
//		CMCLogonStep3_FORM.put("URL","StoreLanguageSelection");
//		CMCLogonStep3_FORM.put("logonId","");
//		CMCLogonStep3_FORM.put("logonPassword","");
	}
	
	private static Map<String, String> CMCGetManageDirectoryStep5_FORM = new LinkedHashMap<String, String>();
	static{
//		CMCLogonStep3_FORM.put("BrowserOk","true");
//		CMCLogonStep3_FORM.put("XMLFile","common.mcLogon");
//		CMCLogonStep3_FORM.put("slurl","StoreLanguageSelection");
//		CMCLogonStep3_FORM.put("mcurl","MerchantCenterView?XMLFile=common.merchantCenter");
//		CMCLogonStep3_FORM.put("reLogonURL","ToolsLogon?XMLFile=common.mcLogon");		
//		CMCLogonStep3_FORM.put("URL","StoreLanguageSelection");
//		CMCLogonStep3_FORM.put("logonId","");
//		CMCLogonStep3_FORM.put("logonPassword","");
	}
	
//	private static Map<String, String> CMCAttachmentFileUploadStep6_FORM = new LinkedHashMap<String, String>();
//	static{
//		CMCLogonStep3_FORM.put("BrowserOk","true");
//		CMCLogonStep3_FORM.put("XMLFile","common.mcLogon");
//		CMCLogonStep3_FORM.put("slurl","StoreLanguageSelection");
//		CMCLogonStep3_FORM.put("mcurl","MerchantCenterView?XMLFile=common.merchantCenter");
//		CMCLogonStep3_FORM.put("reLogonURL","ToolsLogon?XMLFile=common.mcLogon");		
//		CMCLogonStep3_FORM.put("URL","StoreLanguageSelection");
//		CMCLogonStep3_FORM.put("logonId","");
//		CMCLogonStep3_FORM.put("logonPassword","");
//	}
	
	protected void executeTask() throws TaskFailException{
		try {
			CMCLogonStep1();
			CMCLogonStep2();
			CMCGetResourceBundleStep3();
			CMCFindStoreStep4();
			CMCGetManageDirectoryStep5();
			CMCAttachmentFileUploadStep6();
		} catch (Exception e) {
			// TODO: handle exception
			throw new TaskFailException(e);
		}


	}

	private void CMCLogonStep1() throws TaskFailException,Exception {
		WebHit("https://standardhost/lobtools", WEB_FORM_GET);
	}
	
	private void CMCLogonStep2() throws TaskFailException{		
		putParameterInMap(CMCLogonStep2_FORM, "logonId", "wcsadmin");
		putParameterInMap(CMCLogonStep2_FORM, "password", "wcs1admin");
		
		WebHit("https://standardhost/lobtools/cmc/Logon?requestIdentifier=1&locale=zh%5FCN&channelId=%2D4", WEB_FORM_POST, CMCLogonStep2_FORM);
		
		putParameterInReusableMap("identityId");
		putParameterInReusableMap("identitySignature");
	}
	
	private void CMCGetResourceBundleStep3() throws TaskFailException {

		putParameterInMap(CMCGetResourceBundleStep3_FORM, "requestIdentifier", "12");
		putParameterInMap(CMCGetResourceBundleStep3_FORM, "locale", "en_US");
		putParameterInMap(CMCGetResourceBundleStep3_FORM, "developmentMode", "false");
		putParameterInMap(CMCGetResourceBundleStep3_FORM, "extensionBaseName", "extension.attachment.AttachmentLOB");
		putParameterInMap(CMCGetResourceBundleStep3_FORM, "baseName", "com.ibm.commerce.attachment.client.lobtools.properties.AttachmentLOB");
		
		WebHit("https://standardhost/lobtools/cmc/GetResourceBundle", WEB_FORM_GET, CMCGetResourceBundleStep3_FORM);

	}
	
	private void CMCFindStoreStep4() throws TaskFailException {
		putParameterInMap(CMCFindStoreStep4_FORM, "identitySignature", getParameterFromReusableMap("identitySignature"));
		putParameterInMap(CMCFindStoreStep4_FORM, "identityId", getParameterFromReusableMap("identityId"));
		
		WebHit("https://standardhost/lobtools/cmc/FindStores?requestIdentifier=1&timeZoneId=America%2FNew%5FYork&locale=en%5FUS&&recordSetStartNumber=0&maxItems=10&usage=", WEB_FORM_POST, CMCFindStoreStep4_FORM);
		
	}
	
	private void CMCGetManageDirectoryStep5() throws TaskFailException {
		
		putParameterInMap(CMCGetManageDirectoryStep5_FORM, "identitySignature", getParameterFromReusableMap("identitySignature"));
		putParameterInMap(CMCGetManageDirectoryStep5_FORM, "identityId", getParameterFromReusableMap("identityId"));
		
		WebHit("https://standardhost/lobtools/cmc/GetManagedDirectoryChildren?requestIdentifier=1&timeZoneId=America%2FNew%5FYork&locale=en%5FUS&maxItems=25&parentPath=&displayName=Elite&storeId=512&parentId=10001&dataLanguageIds=%2D1", WEB_FORM_POST, CMCGetManageDirectoryStep5_FORM);
		
	}
	
	private void CMCAttachmentFileUploadStep6() throws TaskFailException,Exception
	{
		//=================Create a file for upload purpose only, in a real task these lines are not needed===============================
		String fileName="test"+System.currentTimeMillis()/1000;
		String filePath=fileName;
		try {
			File file=new File(filePath);
			if(!file.exists())
				file.createNewFile();
			DataOutputStream outs = new DataOutputStream(new FileOutputStream(file));
			outs.write(file.getPath().getBytes()); 
			outs.close();
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		//=================Create File,for test===============================
		
		// Add dynamically changed URL parameters begin
		try {
			HTTPMultipartEntity reqEntity = new HTTPMultipartEntity();
			HTTPFileBody fileBody = new HTTPFileBody(new File(filePath), "application/octet-stream");
			reqEntity.addPart("Filename", new HTTPStringBody(fileName));
			reqEntity.addPart("Upload", new HTTPStringBody("Submit Query"));
			reqEntity.addPart("FileData", fileBody);
			
			WebHit("https://standardhost/lobtools/cmc/AttachmentFileUpload?requestIdentifier=1&timeZoneId=America" +
					"%2FNew%5FYork&locale=en%5FUWS&" +
					"identitySignature="+getParameterFromReusableMap("identitySignature")+
					"&identityId="+getParameterFromReusableMap("identityId")+
					"&operationType=Create&parentDirectoryName" +
					"=Attachment&parentDirectoryParentPath=%2FElite&storeId=512&" +
					"fileName="+fileName+
					"&fullPath=/Elite/Attachment&objectStoreId=512&changeControlModifiable=&fileSize=4&sourceFileName=firstTest%2Etxt",WEB_FORM_POST_BIN,reqEntity);
	

		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
